package cn.iocoder.yudao.module.cmt.service.base;

import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.cmt.controller.admin.base.vo.*;
import cn.iocoder.yudao.module.cmt.dal.dataobject.base.BaseMerchantApplyDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.cmt.dal.mysql.base.BaseMerchantApplyMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.cmt.enums.ErrorCodeConstants.*;

/**
 * 商户入驻申请 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class BaseMerchantApplyServiceImpl implements BaseMerchantApplyService {

    @Resource
    private BaseMerchantApplyMapper merchantApplyMapper;

    @Override
    public Long createMerchantApply(BaseMerchantApplySaveReqVO createReqVO) {
        // 插入
        BaseMerchantApplyDO merchantApply = BeanUtils.toBean(createReqVO, BaseMerchantApplyDO.class);
        merchantApplyMapper.insert(merchantApply);
        // 返回
        return merchantApply.getId();
    }

    @Override
    public void updateMerchantApply(BaseMerchantApplySaveReqVO updateReqVO) {
        // 校验存在
        validateMerchantApplyExists(updateReqVO.getId());
        // 更新
        BaseMerchantApplyDO updateObj = BeanUtils.toBean(updateReqVO, BaseMerchantApplyDO.class);
        merchantApplyMapper.updateById(updateObj);
    }

    @Override
    public void deleteMerchantApply(Long id) {
        // 校验存在
        validateMerchantApplyExists(id);
        // 删除
        merchantApplyMapper.deleteById(id);
    }

    private void validateMerchantApplyExists(Long id) {
        if (merchantApplyMapper.selectById(id) == null) {
            throw exception(MERCHANT_APPLY_NOT_EXISTS);
        }
    }

    @Override
    public BaseMerchantApplyDO getMerchantApply(Long id) {
        return merchantApplyMapper.selectById(id);
    }

    @Override
    public PageResult<BaseMerchantApplyDO> getMerchantApplyPage(BaseMerchantApplyPageReqVO pageReqVO) {
        return merchantApplyMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteMerchantApplyListByIds(List<Long> ids) {
        // 校验存在
        ids.forEach(this::validateMerchantApplyExists);
        // 批量删除
        merchantApplyMapper.deleteBatchIds(ids);
    }

}
